//
//  XGL_PersonalCommentView.swift
//  XGamesLive
//
//  Created by ios on 2024/5/21.
//

import UIKit

class XGL_PersonalCommentView: UIView {
    var contentView: UIView!
    var countText: UILabel!
    var tableView: UITableView!
    var datasource: [PublishCommentData] = []
    
    
    var commentCount: NSInteger = 0{
        didSet{
            self.countText.text = self.commentCount.description
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createXglView()
        tableView.addObserver(self, forKeyPath: "contentSize", options: [.new, .old, .prior], context: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutIfNeeded()
        self.contentView.addCorner(conrners: [.topLeft], radius: 24.0)
    }
    
    deinit {
        self.tableView.removeObserver(self, forKeyPath: "contentSize")
    }
}

extension XGL_PersonalCommentView{
    private func thumbCommentRequest(id: String,isThumb: Bool){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Handler(auditTreeDataId: id, type: 2, actionResult: isThumb))) { result in
            switch result{
            case .success(let response):
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalCommentView{
   
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "contentSize" {
            // content size changed
            let height = self.tableView.contentSize.height
            print("tableview 高度:\(height)")
            self.contentView.snp.updateConstraints { (make) in
                make.height.equalTo(height > 0 ? (height + 60.0) : 0 )
            }
            self.isHidden = height == 0
        }
    }
    
    @objc private func thumbCommentItemAction(sender: UIButton){
        sender.isSelected = !sender.isSelected
        let index = sender.tag - 1500
        if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? XGL_PersonalCommentTableViewCell{
            if sender.isSelected{
                cell.thumbCount += 1
            }else{
                cell.thumbCount -= 1
            }
        }
        let data = self.datasource[index]
        self.thumbCommentRequest(id: data.id, isThumb: sender.isSelected)
    }
}

extension XGL_PersonalCommentView: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.datasource.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: XGL_PersonalCommentTableViewCell.self)
        cell.itemThumbButton.tag = indexPath.row + 1500
        cell.itemThumbButton.addTarget(self, action: #selector(self.thumbCommentItemAction(sender:)), for: .touchUpInside)
        cell.itemData = self.datasource[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
}


extension XGL_PersonalCommentView{
    private func createXglView(){
        self.contentView = UIView().then({ make in
            make.backgroundColor = UIColor.hexColor("#001310")
        })
        let titleText = UILabel().then { make in
            make.text = "Comment"
            make.textColor = .white
            make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
        }
        let line = UIView().then { make in
            make.backgroundColor = UIColor.hexColor("#80FFE6")
        }
        self.countText = UILabel().then({ make in
            make.textColor = UIColor.hexColor("#B2B2B2")
            make.font = UIFont.pingfangSC_Semibold(fontSize: 14.0)
        })
        self.tableView = UITableView().then({ make in
            make.register(cellWithClass: XGL_PersonalCommentTableViewCell.self)
            make.dataSource = self
            make.delegate = self
            make.backgroundColor = UIColor.clear
            make.rowHeight = UITableView.automaticDimension
            make.estimatedRowHeight = 150
            make.separatorStyle = .none
        })
       
        contentView.addSubviews([titleText,line,countText,tableView])
        self.addSubview(contentView)
        
        titleText.snp.makeConstraints { make in
            make.left.equalTo(16.0)
            make.top.equalTo(14.0)
        }
        line.snp.makeConstraints { make in
            make.centerX.equalTo(titleText)
            make.width.equalTo(24.0)
            make.height.equalTo(4.0)
            make.top.equalTo(titleText.snp.bottom).offset(12.0)
        }
        countText.snp.makeConstraints { make in
            make.centerY.equalTo(titleText)
            make.left.equalTo(titleText.snp.right).offset(9.0)
        }
        
        
        self.tableView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(line.snp.bottom).offset(8.0)
        }
        contentView.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.right.equalToSuperview()
            make.height.equalTo(0)
        }
        self.snp.makeConstraints { make in
            make.bottom.equalTo(contentView)
        }
    }
}
